package com.chixing.work;

import com.chixing.controller.WebSocketProcess;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * MQ消费者：  通过 websocket 推送 评论消息 给B用户
 * 1. B用户 在线： ws 直接推送 消息
 * 2. B用户 离线： 消息 保存到 Redis (list)
 */
@Component
public class MessageConsumer {
    @Autowired
    private WebSocketProcess webSocketProcess;
    @Autowired
    private ObjectMapper objectMapper;

    @RabbitListener(queues = "wsQueue")
    public void pushMessageToUser(Map<String, Object> map, Message message, Channel channel) {
        try {
            // 从消息体中获取接收者ID和内容
            Long toUserId = Long.parseLong(map.get("toUserId").toString());
            String content = objectMapper.writeValueAsString(map); // 序列化业务数据为JSON

            // 调用WebSocket推送
            boolean isOnline = webSocketProcess.sendMessage(toUserId, content);
            System.out.println("向用户"+toUserId+"推送评论回复消息："+content + "在线状态：" +isOnline);

            // 手动确认消息已消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            System.out.println("消息消费失败");
            // 处理失败时拒绝消息，避免重复消费
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ie) {
                System.out.println("消息消费失败");
            }
        }
    }
}
